package com.good.child.widgets.editext;

import android.text.InputFilter;
import android.text.Spanned;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Create on: 2024/2/27
 * by Mr.Zhu
 * Description: TODO
 */
public class DecimalFilter implements InputFilter {
    private static final String TAG = "DecimalFilter";
    private int lengthBeforeDot;
    private int lengthAfterDot;
    Pattern mPattern;//正则

    public DecimalFilter(int lengthBeforeDot, int lengthAfterDot) {
        this.lengthBeforeDot = lengthBeforeDot;
        this.lengthAfterDot = lengthAfterDot;
        createPattern(lengthBeforeDot, lengthAfterDot);
    }

    protected void createPattern(int lengthBeforeDot, int lengthAfterDot) {
        String pattern = "([0-9]|,){0," + lengthBeforeDot + "}+((\\.[0-9]{0," + lengthAfterDot + "})?)||(\\.)?";//小数
        mPattern = Pattern.compile(pattern);
    }


    public void setPointerLeftLength(int pointerLeftLength) {
        this.lengthBeforeDot = pointerLeftLength;
        createPattern(lengthBeforeDot, lengthAfterDot);
    }

    public void setPointerRightLength(int pointerRightLength) {
        this.lengthAfterDot = pointerRightLength;
        createPattern(lengthBeforeDot, lengthAfterDot);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
//        String sourceText = source.toString();
        //以点开始的时候，自动在前面添加0
        if (source.toString().equals(".") && dstart == 0) {
            return "0.";
        }
        //如果起始位置为0,且第二位跟的不是".",则无法后续输入
        if (!source.toString().equals(".") && dest.toString().equals("0")) {
            return "";
        }
        String formatedSource = source.subSequence(start, end).toString();
        String destPrefix = dest.subSequence(0, dstart).toString();
        String destSuffix = dest.subSequence(dend, dest.length()).toString();
        //算出变化后的值:
        String result = destPrefix + formatedSource + destSuffix;
        if(".".equals(result))
            return "0";
        Matcher matcher = mPattern.matcher(result);
        if (!matcher.matches()) {
            String old = dest.subSequence(dstart, dend).toString();
            return old;//过滤,返回被替换前的原始值
        }
        return null;//不过滤
    }
}
